package com.xbongbong.paas.data.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.CabinetFileService;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.model.ContractCompareUserModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.pojo.AddMuchFieldPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.cabinetfile.pojo.CabinetFilePojo;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileDeleteDTO;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileDownLoadLogDTO;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileGetDTO;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileListGetDTO;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileSaveDTO;
import com.xbongbong.pro.cabinetfile.pojo.vo.CabinetFileDeleteVO;
import com.xbongbong.pro.cabinetfile.pojo.vo.CabinetFileDownLoadLogVO;
import com.xbongbong.pro.cabinetfile.pojo.vo.CabinetFileGetVO;
import com.xbongbong.pro.cabinetfile.pojo.vo.CabinetFileListGetVO;
import com.xbongbong.pro.cabinetfile.pojo.vo.CabinetFileSaveVO;
import com.xbongbong.pro.enums.CabinetFileTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.CabinetFileEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.model.CabinetFileModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ContractCompareUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 *
 * @author 魏荣杰
 * @date 2019/6/20 15:52
 * @since v1.0
 * @version v1.0
 */
@Service("cabinetFileService")
public class CabinetFileServiceImpl implements CabinetFileService {
    private static final Logger LOG = LoggerFactory.getLogger(CabinetFileServiceImpl.class);

    @Resource
    private CabinetFileModel cabinetFileModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;
    @Resource
    private ProductModel productModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private ContractCompareUserModel contractCompareUserModel;
    @Resource
    private ContractCompareUtil contractCompareUtil;


    @Override
    public CabinetFileSaveVO saveCabinetFiles(CabinetFileSaveDTO cabinetFileSaveDTO) throws XbbException {
        CabinetFileSaveVO cabinetFileSaveVO = new CabinetFileSaveVO();
        String corpid = cabinetFileSaveDTO.getCorpid();
        String userId = cabinetFileSaveDTO.getUserId();
        Integer businessType = cabinetFileSaveDTO.getBusinessType();
        Long dataId = cabinetFileSaveDTO.getDataId();
        Long refId = cabinetFileSaveDTO.getRefId();
        if (Objects.equals(cabinetFileSaveDTO.getType(), CabinetFileTypeEnum.STAGE_UPLOAD.getType()) &&
                Objects.isNull(refId)) {
            LOG.error("CabinetFileServiceImpl.saveCabinetFiles error：STAGE_UPLOAD - No refId");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        List<PaasAttachmentEntityExt> cabinetFileList = cabinetFileSaveDTO.getCabinetFileList();
        List<CabinetFileEntity> cabinetFileEntityList = new ArrayList<>();
        for (PaasAttachmentEntityExt cabinetFilePojo : cabinetFileList) {
            CabinetFileEntity cabinetFileEntity = new CabinetFileEntity();
            BeanUtil.copyProperties(cabinetFilePojo, cabinetFileEntity);
            cabinetFileEntity.setCorpid(corpid);
            cabinetFileEntity.setUserId(userId);
            cabinetFileEntity.setBusinessType(businessType);
            cabinetFileEntity.setDataId(dataId);
            cabinetFileEntity.setType(cabinetFileSaveDTO.getType());
            cabinetFileEntity.setRefId(refId);
            if (Objects.isNull(cabinetFileEntity.getAttachIndex())) {
                cabinetFileEntity.setAttachIndex("");
            }
            String validFileName = StringUtil.filterEmoji(cabinetFileEntity.getFilename());
            cabinetFileEntity.setFilename(validFileName);
            cabinetFileEntityList.add(cabinetFileEntity);
        }
        try {
            cabinetFileModel.insertBatch(cabinetFileEntityList);
        } catch (Exception e) {
            LOG.error("CabinetFileServiceImpl.saveCabinetFiles error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        // 文件柜新增日志
        if (cabinetFileEntityList.size() > 0) {
            Runnable runnable = () -> {
                try {
                    // 文件名称
                    List<String> cabinetFileNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    cabinetFileList.forEach(cabinetFile -> cabinetFileNameList.add(cabinetFile.getFilename()));
                    // 查询关联实体对象
                    XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                    String xbbRefName = xbbRefTypeEnum.getName();
                    String logName = logForCabinetFileName(dataId, businessType, corpid);

                    String nameStr = StringUtils.join(cabinetFileNameList, "，");
                    String loginUserName = cabinetFileSaveDTO.getLoginUserName();
                    String memo;
                    if(Objects.equals(cabinetFileNameList.size(), 1)){
                        if(logName != null){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MAIN_USER), loginUserName, xbbRefName, logName, OperateModuleTypeEnum.CABINET.getName(), nameStr);
                        } else {
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), loginUserName, OperateModuleTypeEnum.CABINET.getName(), nameStr);
                        }
                        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.CABINET, OperateTypeEnum.NEW,
                                cabinetFileEntityList.get(0).getId().toString(), nameStr, memo, cabinetFileSaveDTO.getHttpHeader());
                    } else if(cabinetFileNameList.size() > 1){
                        if(logName != null){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_MAIN_USER), loginUserName, xbbRefName, logName, OperateModuleTypeEnum.CABINET.getName());
                        } else {
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_FORM_DETAIL), loginUserName, OperateModuleTypeEnum.CABINET.getName(), cabinetFileNameList.size());
                        }
                        List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        InfoArrPojo infoArrPojo = new InfoArrPojo();
                        infoArrPojo.setTitle(OperateModuleTypeEnum.CABINET.getName());
                        infoArrPojo.setContent(nameStr);
                        infoArrPojoList.add(infoArrPojo);
                        try {
                            mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.CABINET, OperateTypeEnum.NEW,
                                    "", "", memo, cabinetFileSaveDTO.getHttpHeader());
                        } catch (XbbException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (XbbException e) {
                    LOG.error("com.xbongbong.service.impl.CabinetFileServiceImpl.saveCabinetFiles error", e);
                }
            };
            logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
        }

        return cabinetFileSaveVO;
    }

    @Override
    public CabinetFileGetVO getCabinetFiles(CabinetFileGetDTO cabinetFileGetDTO) throws XbbException {
        CabinetFileGetVO cabinetFileGetVO = new CabinetFileGetVO();
        try {
            String corpid = cabinetFileGetDTO.getCorpid();
            Integer businessType = cabinetFileGetDTO.getBusinessType();
            Long dataId = cabinetFileGetDTO.getDataId();
            Integer type = cabinetFileGetDTO.getType();
            Long refId = cabinetFileGetDTO.getRefId();
            List<CabinetFileEntity> cabinetFiles;
            if (Objects.nonNull(businessType)) {
                //saas
                cabinetFiles = cabinetFileModel.getCabinetFiles(corpid, dataId, businessType, type, refId);
            } else {
                //paas
                cabinetFiles = cabinetFileModel.getCabinetFiles(corpid, dataId, null, type, refId);
            }
            cabinetFileGetVO.setCabinetFileList(cabinetFiles);
        } catch (Exception e) {
            LOG.error("CabinetFileServiceImpl.getCabinetFiles error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return cabinetFileGetVO;
    }

    @Override
    public void saveDataCabinetFile(Map<String, FieldAttrEntity> explainMap, JSONObject data, JSONObject subFormData, String corpid, Long dataId, Integer businessType, String userId) throws XbbException {
        List<String> uploadAttr = new ArrayList<>();
        Set<String> subFormAttr = new HashSet<>();
        Map<String, String> subFormUploadMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取附件字段
        getFileFieldList(explainMap, uploadAttr, subFormAttr, subFormUploadMap);
        if (CollectionsUtil.isEmpty(uploadAttr) && subFormUploadMap.isEmpty()) {
            // 没有附件字段，下面的逻辑无需执行
            return;
        }
        //普通附件字段获取上传的文件
        List<PaasAttachmentEntityExt> cabinetFileEntities = getAttachmentList(uploadAttr, data, subFormData, subFormAttr, explainMap, subFormUploadMap);

        saveFile(cabinetFileEntities, CabinetFileTypeEnum.NORMAL.getType(), corpid, dataId, businessType, userId);
    }

    @Override
    public void saveDataCabinetFile(Map<String, FieldAttrEntity> explainMap, PaasFormDataEntity paasFormDataEntity, String corpid, Long dataId, Integer businessType, String userId) throws XbbException {
        List<String> uploadAttr = new ArrayList<>();
        Set<String> subFormAttr = new HashSet<>();
        Map<String, String> subFormUploadMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取附件字段
        getFileFieldList(explainMap, uploadAttr, subFormAttr, subFormUploadMap);
        if (CollectionsUtil.isEmpty(uploadAttr) && subFormUploadMap.isEmpty()) {
            // 没有附件字段，下面的逻辑无需执行
            return;
        }
        JSONObject data = paasFormDataEntity.getData();
        //普通附件字段获取上传的文件
        List<PaasAttachmentEntityExt> cabinetFileEntities = getAttachmentList(uploadAttr, data, paasFormDataEntity.getSubFormData(), subFormAttr, explainMap, subFormUploadMap);

        saveFile(cabinetFileEntities, CabinetFileTypeEnum.NORMAL.getType(), corpid, dataId, businessType, userId);
    }

    @Override
    public void saveDataCabinetFile4StageThruster(List<PaasAttachmentEntityExt> cabinetFileEntities, String corpid, Long dataId, Integer businessType, String userId, Long refId) throws XbbException {
        saveFile(cabinetFileEntities, CabinetFileTypeEnum.STAGE_UPLOAD.getType(), corpid, dataId, businessType, userId, refId);
    }


    /**
     * 获取上传的附件
     * @param uploadAttr 附件字段
     * @param data 数据
     * @param subFormData 子表单数据
     * @param subFormAttr 子表单字段（子表单和关联产品）
     * @param explainMap 字段容器
     * @param subFormUploadMap 子表单附件字段
     * @return 返回附件
     */
    private List<PaasAttachmentEntityExt> getAttachmentList(List<String> uploadAttr, JSONObject data, JSONObject subFormData, Set<String> subFormAttr, Map<String, FieldAttrEntity> explainMap, Map<String, String> subFormUploadMap) {
        List<PaasAttachmentEntityExt> cabinetFileEntities = new ArrayList<>();
        for (String attr : uploadAttr) {
            String uploadStr = data.getString(attr);
            if (Objects.nonNull(uploadStr)) {
                List<PaasAttachmentEntityExt> filePojos = JSONArray.parseArray(uploadStr, PaasAttachmentEntityExt.class);
                if (Objects.nonNull(filePojos)) {
                    cabinetFileEntities.addAll(filePojos);
                }
            }
        }
        //子表单内附件字段上传的文件
        for (String attr : subFormAttr) {
            JSONArray subFormArray = new JSONArray();
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), explainMap.get(attr).getFieldType())) {
                subFormArray = Objects.isNull(subFormData) ? new JSONArray() : subFormData.getJSONArray(attr);
            } else if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), explainMap.get(attr).getFieldType())){
                subFormArray = data.getJSONArray(attr);
            }
            if (Objects.nonNull(subFormArray) && !subFormArray.isEmpty()) {
                for (Object object : subFormArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    String subUploadAttr = subFormUploadMap.get(attr);
                    if (Objects.nonNull(subUploadAttr)) {
                        String subUploadStr = jsonObject.getString(subUploadAttr);
                        if (Objects.nonNull(subUploadStr)) {
                            List<PaasAttachmentEntityExt> subAttachments = JSONArray.parseArray(subUploadStr, PaasAttachmentEntityExt.class);
                            if (Objects.nonNull(subAttachments)) {
                                cabinetFileEntities.addAll(subAttachments);
                            }
                        }
                    }
                }
            }
        }
        return cabinetFileEntities;
    }

    /**
     * 获取附件字段
     * @param explainMap
     * @param uploadAttr 子表单外的附件字段
     * @param subFormAttr 子表单字段或者关联字段
     * @param subFormUploadMap 子表单内附件字段
     * @return void
     * @author 吴峰
     * @date 2021/2/25 11:01
     * @throws XbbException
     */
    private void getFileFieldList(Map<String, FieldAttrEntity> explainMap, List<String> uploadAttr, Set<String> subFormAttr, Map<String, String> subFormUploadMap) {
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity fieldAttrEntity = entry.getValue();
            //启用的并且类型为附件
            List<Integer> subFieldList = Arrays.asList(FieldTypeEnum.SUB_FORM.getType(), FieldTypeEnum.SELECT_PRODUCT.getType());
            if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                uploadAttr.add(fieldAttrEntity.getAttr());
            }
            if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && subFieldList.contains(fieldAttrEntity.getFieldType())) {
                //获取子表单内的附件字段
                List<? extends FieldAttrEntity> fieldAttrEntities = fieldAttrEntity.getSubForm().getItems();
                for (FieldAttrEntity subFieldEntity : fieldAttrEntities) {
                    if (Objects.equals(subFieldEntity.getIsOpen(), 1) && Objects.equals(subFieldEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                        subFormAttr.add(fieldAttrEntity.getAttr());
                        subFormUploadMap.put(fieldAttrEntity.getAttr(), subFieldEntity.getAttr());
                    }
                }
            }
        }
    }

    /**
     * 存储附件的逻辑，整理成一个方法，由上面的方法调用
     * @param cabinetFileEntities 附件字段
     * @param type 文件柜文件上传来源  - see CabinetFileTypeEnum
     * @param corpid 公司id
     * @param dataId 数据id
     * @param businessType 业务类型
     * @param userId 用户id
     * @param refId stageWorkId
     * @return void
     * @author 吴峰
     * @date 2021/2/25 11:02
     * @throws XbbException
     */
    private void saveFile(List<PaasAttachmentEntityExt> cabinetFileEntities, Integer type, String corpid, Long dataId, Integer businessType, String userId, Long refId) throws XbbException{
        //去重
        Set<String>  indexSet = new HashSet<>();
        List<PaasAttachmentEntityExt> cabinetFileFilter = new ArrayList<>();
        for (PaasAttachmentEntityExt paasAttachmentEntityExt : cabinetFileEntities) {
            if (!indexSet.contains(paasAttachmentEntityExt.getAttachIndex())) {
                indexSet.add(paasAttachmentEntityExt.getAttachIndex());
                cabinetFileFilter.add(paasAttachmentEntityExt);
            }
        }
        // bug-id:37843 edit @date 2021/4/2 10:21 在这里对特殊的回款单，付款单做下转化业务类型，因为文件柜那边传的是回款单和付款单的业务类型，如果存其他的话，在文件柜中无法看见附件；
        SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
        boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
        if (sheetFlag) {
            businessType = sheetTypeEnum.getXbbRefTypeEnum().getCode();
        }

        List<CabinetFileEntity> cabinetFileDBList;
        if (!Objects.equals(businessType, 0)) {
            //saas
            cabinetFileDBList = cabinetFileModel.getCabinetFiles(corpid, dataId, businessType, type, refId);
        } else {
            //paas
            cabinetFileDBList = cabinetFileModel.getCabinetFiles(corpid, dataId, null, type, refId);
        }

        Map<String, CabinetFileEntity> cabinetFileEntityMap = new HashMap<>(cabinetFileDBList.size());
        for (CabinetFileEntity entity : cabinetFileDBList) {
            cabinetFileEntityMap.put(entity.getAttachIndex(), entity);
        }
        //需要保留的文件
        List<CabinetFileEntity> keepFileList = new ArrayList<>();
        //新增的需要插入数据的文件
        List<PaasAttachmentEntityExt> insertFileList = new ArrayList<>();
        for (PaasAttachmentEntityExt pojo : cabinetFileFilter) {
            if (cabinetFileEntityMap.containsKey(pojo.getAttachIndex())) {
                keepFileList.add(cabinetFileEntityMap.get(pojo.getAttachIndex()));
            } else {
                insertFileList.add(pojo);
            }
        }
        //要删除的文件
        List<CabinetFileEntity> deleteFileList = new ArrayList<>(cabinetFileDBList);
        deleteFileList.removeAll(keepFileList);
        List<Long> deleteIds = new ArrayList<>();
        for (CabinetFileEntity entity : deleteFileList) {
            deleteIds.add(entity.getId());
        }
        //删除文件
        if (deleteIds.size() > 0) {
            cabinetFileModel.deleteBatch(deleteIds, corpid);
        }

        //保存新的文件
        if (insertFileList.size() > 0) {
            // 员工离职兼容
            UserEntity user = userModel.getByKeyIngoreDel(userId, corpid);
            CabinetFileSaveDTO cabinetFileSaveDTO = new CabinetFileSaveDTO(insertFileList, businessType, dataId);
            cabinetFileSaveDTO.setCorpid(corpid);
            cabinetFileSaveDTO.setUserId(userId);
            cabinetFileSaveDTO.setType(type);
            cabinetFileSaveDTO.setRefId(refId);
            // 日志需要
            cabinetFileSaveDTO.setLoginUserName(Objects.isNull(user) ? "" : user.getName());
            saveCabinetFiles(cabinetFileSaveDTO);
        }
    }

    private void saveFile(List<PaasAttachmentEntityExt> cabinetFileEntities, Integer type, String corpid, Long dataId, Integer businessType, String userId) throws XbbException{
        saveFile(cabinetFileEntities, type, corpid, dataId, businessType, userId, null);
    }

    /**
     * 批量增加业务时需要批量处理图片
     *
     * @param explainMap 解释
     * @param insertList 这是带有id的插入列表
     * @param updateBatchList 更新数据列表
     * @param delBatchList 删除数据列表
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param userId 用户id
     * @throws XbbException
     */
    @Override
    public void saveBatchCabinetFile(Map<String, FieldAttrEntity> explainMap, List<AddMuchFieldPojo> insertList, List<AddMuchFieldPojo> updateBatchList, List<AddMuchFieldPojo> delBatchList, String corpid, Integer businessType, String userId) throws XbbException, InstantiationException, IllegalAccessException {
        List<String> uploadAttr = new ArrayList<>();
        List<String> subFormAttr = new ArrayList<>();
        Map<String, String> subFormUploadMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity fieldAttrEntity = entry.getValue();
            //启用的并且类型为附件
            if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                uploadAttr.add(fieldAttrEntity.getAttr());
            }
            if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                //获取子表单内的附件字段
                subFormAttr.add(fieldAttrEntity.getAttr());
                List<? extends FieldAttrEntity> fieldAttrEntities = fieldAttrEntity.getSubForm().getItems();
                for (FieldAttrEntity subFieldEntity : fieldAttrEntities) {
                    if (Objects.equals(subFieldEntity.getIsOpen(), 1) && Objects.equals(subFieldEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                        subFormUploadMap.put(fieldAttrEntity.getAttr(), subFieldEntity.getAttr());
                    }
                }
            }
        }
        List<AddMuchFieldPojo> dataList = new ArrayList<>();
        dataList.addAll(insertList);
        dataList.addAll(updateBatchList);
        dataList.addAll(delBatchList);
        List<Long> dataIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataIdList = dataList.stream().map(u -> u.getId()).collect(Collectors.toList());
        }
        //普通附件字段获取上传的文件
        List<PaasAttachmentEntityExt> cabinetFileEntities = new ArrayList<>();
        Map<Long,List<PaasAttachmentEntityExt>> idFileMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);


        for (String attr : uploadAttr) {
            for (AddMuchFieldPojo addMuchFieldPojo : dataList) {
                JSONObject data = addMuchFieldPojo.getData();
                String uploadStr = data.getString(attr);
                long id = addMuchFieldPojo.getId();
                if (Objects.nonNull(uploadStr)) {
                    List<PaasAttachmentEntityExt> filePojos = JSONArray.parseArray(uploadStr, PaasAttachmentEntityExt.class);
                    if (Objects.nonNull(filePojos)) {
                        cabinetFileEntities.addAll(filePojos);
                        idFileMap.put(id, filePojos);
                    }
                }
            }
        }
        //子表单内附件字段上传的文件
        for (String attr : subFormAttr) {
            for (AddMuchFieldPojo addMuchFieldPojo : dataList) {
                JSONObject data = addMuchFieldPojo.getData();
                JSONArray subFormArray = data.getJSONArray(attr);
                long id = addMuchFieldPojo.getId();
                if (Objects.nonNull(subFormArray)) {
                    for (Object object : subFormArray) {
                        JSONObject jsonObject = (JSONObject) object;
                        String subUploadAttr = subFormUploadMap.get(attr);
                        if (Objects.nonNull(subUploadAttr)) {
                            String subUploadStr = jsonObject.getString(subUploadAttr);
                            if (Objects.nonNull(subUploadStr)) {
                                List<PaasAttachmentEntityExt> subAttachments = JSONArray.parseArray(subUploadStr, PaasAttachmentEntityExt.class);
                                if (Objects.nonNull(subAttachments)) {
                                    cabinetFileEntities.addAll(subAttachments);
                                    idFileMap.put(id, subAttachments);
                                }
                            }
                        }
                    }
                }
            }
        }
        //去重
        Set<String>  indexSet = new HashSet<>();
        List<PaasAttachmentEntityExt> cabinetFileFilter = new ArrayList<>();
        for (PaasAttachmentEntityExt paasAttachmentEntityExt : cabinetFileEntities) {
            if (!indexSet.contains(paasAttachmentEntityExt.getAttachIndex())) {
                indexSet.add(paasAttachmentEntityExt.getAttachIndex());
                cabinetFileFilter.add(paasAttachmentEntityExt);
            }
        }
        List<CabinetFileEntity> cabinetFileDBList;
        if (!Objects.equals(businessType, 0)) {
            //saas
            cabinetFileDBList = cabinetFileModel.getCabinetFilesByIdIn(corpid, dataIdList, businessType);
        } else {
            //paas
            cabinetFileDBList = cabinetFileModel.getCabinetFilesByIdIn(corpid, dataIdList, null);
        }
        Map<String, CabinetFileEntity> cabinetFileEntityMap = new HashMap<>(cabinetFileDBList.size());
        for (CabinetFileEntity entity : cabinetFileDBList) {
            cabinetFileEntityMap.put(entity.getAttachIndex(), entity);
        }
        //需要保留的文件
        List<CabinetFileEntity> keepFileList = new ArrayList<>();
        //新增的需要插入数据的文件
        List<PaasAttachmentEntityExt> insertFileList = new ArrayList<>();
        for (PaasAttachmentEntityExt pojo : cabinetFileFilter) {
            if (cabinetFileEntityMap.containsKey(pojo.getAttachIndex())) {
                keepFileList.add(cabinetFileEntityMap.get(pojo.getAttachIndex()));
            } else {
                insertFileList.add(pojo);
            }
        }
        //要删除的文件
        List<CabinetFileEntity> deleteFileList = new ArrayList<>(cabinetFileDBList);
        deleteFileList.removeAll(keepFileList);
        List<Long> deleteIds = new ArrayList<>();
        for (CabinetFileEntity entity : deleteFileList) {
            deleteIds.add(entity.getId());
        }
        //删除文件
        if (deleteIds.size() > 0) {
            cabinetFileModel.deleteBatch(deleteIds, corpid);
        }

        //拼接需要保存新的文件
        List<CabinetFileEntity> cabinetFileEntityInsertList = new ArrayList<>();
        if (insertFileList.size() > 0) {
            long time = DateUtil.getInt();
            for (PaasAttachmentEntityExt paasAttachmentEntityExt : insertFileList) {
                for (Long id : idFileMap.keySet()) {
                    List<PaasAttachmentEntityExt> paasAttachmentEntityExts = idFileMap.get(id);
                    for (PaasAttachmentEntityExt paasAttachmentEntityExtSen : paasAttachmentEntityExts) {
                        if (paasAttachmentEntityExtSen.getAttachIndex().equals(paasAttachmentEntityExt.getAttachIndex())) {
                            CabinetFileEntity cabinetFileEntity = new CabinetFileEntity();
                            cabinetFileEntity.setCorpid(corpid);
                            cabinetFileEntity.setUserId(userId);
                            cabinetFileEntity.setBusinessType(businessType);
                            cabinetFileEntity.setDataId(id);
                            cabinetFileEntity.setFilename(paasAttachmentEntityExt.getFilename());
                            cabinetFileEntity.setAttachIndex(paasAttachmentEntityExt.getAttachIndex());
                            cabinetFileEntity.setExt(paasAttachmentEntityExt.getExt());
                            cabinetFileEntity.setSize(paasAttachmentEntityExt.getSize());
                            cabinetFileEntity.setAddTime(time);
                            cabinetFileEntity.setDel(BasicConstant.ZERO);
                            cabinetFileEntity.setType(BasicConstant.ONE);
                            cabinetFileEntityInsertList.add(cabinetFileEntity);
                        }
                    }
                }
                // 员工离职兼容
               /* UserEntity user = userModel.getByKeyIngoreDel(userId, corpid);
                CabinetFileSaveDTO cabinetFileSaveDTO = new CabinetFileSaveDTO();
                cabinetFileSaveDTO.setInsertFileList(cabinetFileEntityInsertList);
                cabinetFileSaveDTO.setCabinetFileList(insertFileList);
                // 日志需要
                cabinetFileSaveDTO.setLoginUserName(user.getName());*/
            }
            cabinetFileModel.insertBatch(cabinetFileEntityInsertList);
        }

    }


    @Override
    public CabinetFileListGetVO getCabinetFileList(CabinetFileListGetDTO cabinetFileListGetDTO) throws XbbException {
        CabinetFileListGetVO cabinetFileListGetVO = new CabinetFileListGetVO();
        try {
            String corpid = cabinetFileListGetDTO.getCorpid();
            Integer businessType = cabinetFileListGetDTO.getBusinessType();
            Integer linkBusinessType = cabinetFileListGetDTO.getLinkBusinessType();
            Long dataId = cabinetFileListGetDTO.getDataId();
            Integer saasMark = cabinetFileListGetDTO.getSaasMark();

            Integer page = cabinetFileListGetDTO.getPage();
            Integer pageSize = cabinetFileListGetDTO.getPageSize();
            if (Objects.nonNull(pageSize)) {
                pageSize = 10;
            }
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
            BeanUtil.copyProperties(cabinetFileListGetDTO, verifyViewPermissionDTO);
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && !Objects.equals(linkBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                // 客户的文件柜里，有机会和合同的文件柜tab，所以，这边用linkBusinessType来作为verifyViewPermissionDTO的businessType，来获取文件柜可见权限的枚举
                verifyViewPermissionDTO.setBusinessType(linkBusinessType);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                ProductEntityExt productEntityExt = productModel.getByKey(dataId, corpid);
                if (Objects.nonNull(productEntityExt)) {
                    Long parentId = productEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    if (!Objects.equals(parentId, 0L)) {
                        // 拿下父产品的id，去查询文件柜中的数据
                        dataId = parentId;
                    }
                }
            }
            // 文件柜可见权限校验
            boolean canSee = ProPermissionHelp.verifyFileVisiblePermission(verifyViewPermissionDTO);
            // 文件柜删除权限校验
            boolean canDelete = ProPermissionHelp.verifyFileDeletePermission(verifyViewPermissionDTO);
            if (!canSee) {
                cabinetFileListGetVO.setIsSummit(canDelete);
                cabinetFileListGetVO.setPageHelper(new PageHelper());
                cabinetFileListGetVO.setFiles(new ArrayList<>());
                return cabinetFileListGetVO;
            }

            List<PaasFormDataEntityExt> linkPaasFormDataEntities = new ArrayList<>();
            List<CabinetFileEntity> cabinetFileEntitiesDB = new ArrayList<>();
            PageHelper pageHelper = new PageHelper();
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("del", 0);
            params.put("page", page);
            params.put("orderByStr", "add_time desc");
            if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                if (!Objects.equals(businessType, 0)) {
                    //saas
                    XbbRefTypeEnum businessTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                    XbbRefTypeEnum linkBusinessTypeEnum = XbbRefTypeEnum.getByCode(linkBusinessType);
                    switch (businessTypeEnum) {
                        case CUSTOMER_MANAGEMENT:
                            switch (linkBusinessTypeEnum) {
                                case CUSTOMER_MANAGEMENT:
                                    params.put("dataIdIn", Collections.singletonList(dataId));
                                    params.put("businessType", linkBusinessType);
                                    break;
                                case CONTRACT:
                                    //先找出这个客户的合同，然后根据合同去找文件
                                    BoolQueryBuilder boolQueryBuilder = boolQuery()
                                            .filter(termQuery("corpid.keyword", corpid))
                                            .filter(termQuery("del", 0))
                                            .filter(termQuery("data." + ContractEnum.LINK_CUSTOMER.getAttr(), dataId))
                                            .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                                    List<PaasFormDataEntityExt> contractEsEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, PaasFormDataEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
                                    Set<Long> contractIds = new HashSet<>();
                                    for (PaasFormDataEntityExt entityExt : contractEsEntities) {
                                        contractIds.add(entityExt.getDataId());
                                    }
                                    params.put("dataIdIn", contractIds);
                                    params.put("businessType", linkBusinessType);

                                    linkPaasFormDataEntities = paasEsModel.getByIdList(new ArrayList<>(contractIds), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CONTRACT.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_CONTRACT);
                                    break;
                                case SALES_OPPORTUNITY:
                                    //先找出这个客户的机会，然后根据机会去找文件
                                    BoolQueryBuilder boolQuery = boolQuery()
                                            .filter(termQuery("corpid.keyword", corpid))
                                            .filter(termQuery("del", 0))
                                            .filter(termQuery("data." + SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), dataId))
                                            .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                                    List<PaasFormDataEntityExt> opportunityEsEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OPPORTUNITY, boolQuery, PaasFormDataEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
                                    Set<Long> opportunityIds = new HashSet<>();
                                    for (PaasFormDataEntityExt entityExt : opportunityEsEntities) {
                                        opportunityIds.add(entityExt.getDataId());
                                    }
                                    params.put("dataIdIn", opportunityIds);
                                    params.put("businessType", linkBusinessType);

                                    linkPaasFormDataEntities = paasEsModel.getByIdList(new ArrayList<>(opportunityIds), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
                                    break;
                                default:
                            }
                            break;
                        case CONTRACT_OUTSTOCK:
                        case RETURNED_PURCHASE_OUTSTOCK:
                        case OTHER_OUTSTOCK:
                        case PRODUCTION_MATERIEL_OUTSTOCK:
                        case WORK_ORDER_OUTSTOCK:
                            params.put("dataIdIn", Collections.singletonList(dataId));
                            params.put("businessTypeIn", Arrays.asList(businessType,XbbRefTypeEnum.OUTSTOCK.getCode()));
                            break;
                        case PURCHASE_INSTOCK:
                        case REFUND_INSTOCK:
                        case OTHER_INSTOCK:
                        case PRODUCTION_INSTOCK:
                        case RETURNED_MATERIEL_INSTOCK:
                            params.put("dataIdIn", Collections.singletonList(dataId));
                            params.put("businessTypeIn", Arrays.asList(businessType,XbbRefTypeEnum.INSTOCK.getCode()));
                            break;
                        default:
                            params.put("dataIdIn", Collections.singletonList(dataId));
                            params.put("businessType", businessType);
                            break;
                    }
                    pageHelper = PageHelperUtil.getPageHelper(params, cabinetFileModel, pageSize);
                    cabinetFileEntitiesDB = (List<CabinetFileEntity>) PageHelperUtil.getEntityList(params, pageHelper, cabinetFileModel);
                } else {
                    throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
                }
            } else if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
                //paas
                params.put("dataIdIn", Collections.singletonList(dataId));
                pageHelper = PageHelperUtil.getPageHelper(params, cabinetFileModel, pageSize);
                cabinetFileEntitiesDB = (List<CabinetFileEntity>) PageHelperUtil.getEntityList(params, pageHelper, cabinetFileModel);
            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            Set<String> userIds = new HashSet<>();
            for (CabinetFileEntity entity : cabinetFileEntitiesDB) {
                userIds.add(entity.getUserId());
            }
            List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, new ArrayList<>(userIds), true);
            Map<String, String> userIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (UserEntity entity : userEntities) {
                userIdAndNameMap.put(entity.getUserId(), entity.getName());
            }

            Map<Long, PaasFormDataEntityExt> paasFormDataEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasFormDataEntityExt entityExt : linkPaasFormDataEntities) {
                paasFormDataEntityExtMap.put(entityExt.getId(), entityExt);
            }
            List<CabinetFilePojo> cabinetFilePojoList = new ArrayList<>();
            for (CabinetFileEntity entity : cabinetFileEntitiesDB) {
                CabinetFilePojo cabinetFilePojo = new CabinetFilePojo();
                BeanUtil.copyProperties(entity, cabinetFilePojo);
                cabinetFilePojo.setUserName(userIdAndNameMap.get(entity.getUserId()));

                CabinetFilePojo.DataEntity dataEntity = new CabinetFilePojo.DataEntity();
                PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataEntityExtMap.get(entity.getDataId());
                if (Objects.nonNull(paasFormDataEntityExt)) {
                    dataEntity.setAppId(paasFormDataEntityExt.getAppId());
                    dataEntity.setMenuId(paasFormDataEntityExt.getMenuId());
                    dataEntity.setFormId(paasFormDataEntityExt.getFormId());
                    dataEntity.setSaasMark(saasMark);
                    dataEntity.setDataId(paasFormDataEntityExt.getId());
                    if (Objects.equals(linkBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                        dataEntity.setName(paasFormDataEntityExt.getSerialNo());
                        dataEntity.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                    } else if (Objects.equals(linkBusinessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                        dataEntity.setName(paasFormDataEntityExt.getSerialNo());
                        dataEntity.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                    }
                }
                cabinetFilePojo.setDataEntity(dataEntity);
                cabinetFilePojoList.add(cabinetFilePojo);
            }

            cabinetFileListGetVO.setIsSummit(canDelete);
            cabinetFileListGetVO.setPageHelper(pageHelper);
            cabinetFileListGetVO.setFiles(cabinetFilePojoList);
            List<ButtonPojo> buttonList = new ArrayList<>();
            if ((Objects.equals(cabinetFileListGetDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(cabinetFileListGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE.getCode()))) {
                Boolean showCompareButton = contractCompareUtil.showCompareButton(corpid, cabinetFileListGetDTO.getLoginUser().getPermSet(), cabinetFileListGetDTO.getUserId());
                if (showCompareButton){
                    ButtonPojo buttonPojo = new ButtonPojo();
                    buttonPojo.setAttr(XbbRefTypeEnum.CONTRACT_COMPARE.getAlias());
                    buttonPojo.setValue(XbbRefTypeEnum.CONTRACT_COMPARE.getName());
                    buttonList.add(buttonPojo);
                }
            }
            cabinetFileListGetVO.setButtonList(buttonList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return cabinetFileListGetVO;
    }

    @Override
    public CabinetFileDeleteVO deleteFiles(CabinetFileDeleteDTO cabinetfileDeleteDTO) throws XbbException {
        CabinetFileDeleteVO cabinetFileDeleteVO = new CabinetFileDeleteVO();
        String corpid = cabinetfileDeleteDTO.getCorpid();
        List<Long> dataIds = cabinetfileDeleteDTO.getDataIds();

        // 删除之前用于记录日志
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("idIn", dataIds);
        List<CabinetFileEntity> cabinetFileEntityList = cabinetFileModel.findEntitys(params);

        // 文件柜没有批量删除的入口，不知道荣杰这里用dataIds是几个意思
        Map<Long, String> cabinetFileNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String logName = null;
        String xbbRefName = null;
        for(CabinetFileEntity cabinetFile : cabinetFileEntityList){
            Long refId = cabinetFile.getDataId();
            Integer businessType = cabinetFile.getBusinessType();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            xbbRefName = xbbRefTypeEnum.getName();
            logName = logForCabinetFileName(refId, businessType, corpid);
            cabinetFileNameMap.put(cabinetFile.getId(), cabinetFile.getFilename());
        }

        try {
            cabinetFileModel.deleteBatch(dataIds, corpid);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        // 日志 考虑到不存在批量删除
        List<String> cabinetFileName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        dataIds.forEach(dataId -> {
            if(cabinetFileNameMap.containsKey(dataId)){
                cabinetFileName.add(cabinetFileNameMap.get(dataId));
            }
        });
        String nameStr = StringUtils.join(cabinetFileName, "，");
        String loginUserName = cabinetfileDeleteDTO.getLoginUserName();
        String userId = cabinetfileDeleteDTO.getUserId();
        if(Objects.equals(dataIds.size(), 1)){
            String memo;
            if(logName != null){
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DEL_MAIN_USER), loginUserName, xbbRefName, logName, OperateModuleTypeEnum.CABINET.getName(), nameStr);
            } else {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), loginUserName, OperateModuleTypeEnum.CABINET.getName(), nameStr);
            }
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.CABINET, OperateTypeEnum.DELETE,
                    dataIds.get(0).toString(), nameStr, memo, cabinetfileDeleteDTO.getHttpHeader());
        }
        return cabinetFileDeleteVO;
    }

    /**
     * Description: 下载文件柜 文件日志
     *
     * @param downLoadLogDTO
     * @return CabinetFileDownLoadLogVO
     * @author youli.chen
     * @date 2019/6/26 17:04
     * @since v10
     */
    @Override
    public CabinetFileDownLoadLogVO downLoadLog(CabinetFileDownLoadLogDTO downLoadLogDTO) throws XbbException {
        CabinetFileDownLoadLogVO fileDownLoadLogVO = new CabinetFileDownLoadLogVO();
        String corpid = downLoadLogDTO.getCorpid();
        Integer saasMark = downLoadLogDTO.getSaasMark();
        Integer businessType = downLoadLogDTO.getBusinessType();
        String userId = downLoadLogDTO.getUserId();
        String loginUserName = downLoadLogDTO.getLoginUserName();
        String fileName = downLoadLogDTO.getFileName();

        String memo;
        if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DOWNLOAD_WORK), loginUserName, OperateModuleTypeEnum.CABINET.getName(), fileName);
        } else {
            if (businessType == null || businessType == 0) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            String xbbRefTypeName = xbbRefTypeEnum.getName();
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DOWNLOAD_FILE), loginUserName, xbbRefTypeName, OperateModuleTypeEnum.CABINET.getName(), fileName);
        }
        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.CABINET, OperateTypeEnum.DOWNLOAD,
                "", "", memo, downLoadLogDTO.getHttpHeader());
        return fileDownLoadLogVO;
    }

    /**
     *  获取日志对象名称
     * @param refId
     * @param businessType
     * @param corpid
     * @return
     * @throws XbbException
     */
    private String logForCabinetFileName(Long refId, Integer businessType, String corpid) throws XbbException{
        String logName = null;
        PaasFormDataEntityExt refEntity = formDataHelp.getFormData(refId, corpid, businessType);
        String name;
        StringBuilder sb = new StringBuilder();
        if (refEntity != null) {
            String serialNo = refEntity.getSerialNo();
            JSONObject data = refEntity.getData();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (xbbRefTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                    break;
                case CONTRACT:
                    name = data.getString(ContractEnum.NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case CONTACT:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.NAME.getAttr(), "");
                    break;
                case REFUND:
                    name = data.getString(RefundEnum.REFUND_NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case OUTSTOCK:
                case CONTRACT_OUTSTOCK:
                case RETURNED_PURCHASE_OUTSTOCK:
                case OTHER_OUTSTOCK:
                case PRODUCTION_MATERIEL_OUTSTOCK:
                case WORK_ORDER_OUTSTOCK:
                    logName = serialNo;
                    break;
                case RETURNED_PURCHASE:
                    logName = serialNo;
                    break;
                case SALES_OPPORTUNITY:
                    name = data.getString(SalesOpportunityEnum.NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case BOM_BILL:
                    name = data.getString(BomBillEnum.NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case CUSTOMER_COMMUNICATE:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                    break;
                case SUPPLIER_COMMUNICATE:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
                    break;
                case COMMUNICATE_PLAN:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicatePlanEnum.NAME.getAttr(), "");
                    break;
                case SUPPLIER:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                    break;
                case SUPPLIER_CONTACT:
                    logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                    break;
                case PURCHASE:
                    name = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case PRODUCTION_ORDER:
                    logName = serialNo;
                    break;
                case PAYMENT:
                    logName = serialNo;
                    break;
                case PAY_PLAN:
                    logName = serialNo;
                    break;
                case INVOICE:
                    logName = serialNo;
                    break;
                case INVENTORY:
                    logName = serialNo;
                    break;
                case TRANSFER:
                    logName = serialNo;
                    break;
                case WAREHOUSE:
                    name = data.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
                    logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                    break;
                case PRODUCT:
                    name = data.getString(ProductEnum.NAME.getAttr());
                    String productNo = FastJsonHelper.getStringOrDefaultFromFormData(data, ProductEnum.PRODUCT_NO.getAttr(), "");
                    logName = name == null ? productNo : sb.append(name).append("（").append(productNo).append("）").toString();
                    break;
                case ASSEMBLE:
                    logName = serialNo;
                    break;
                case INSTOCK:
                case PURCHASE_INSTOCK:
                case REFUND_INSTOCK:
                case OTHER_INSTOCK:
                case PRODUCTION_INSTOCK:
                case RETURNED_MATERIEL_INSTOCK:
                    logName = serialNo;
                    break;
                case QUOTATION:
                    logName = serialNo;
                    break;
                default:
                    break;
            }
        }
        return logName;
    }
}
